import { createRouter, createWebHashHistory, type RouteLocation } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import cfg from '@/config/config'
import routes from './routes'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach(async (to : any, from : any) => {
  NProgress.start()
  const store = useUserStore()
  
  if (store.isLoggedIn) {
    if (to.name === 'login') {
      return {name: 'home'}
    } else {
      return true
    }
  } else {
    if (cfg.WhiteList.indexOf(to.name) > -1) {
      return true
    } else {
      return {name: 'login', query: {redirect: document.location.hash.substr(1)}}
    }
  }
  return true
})

router.afterEach((to, from) => {
  NProgress.done()
})

export default router
